<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 6/18/24
 * Time: 1:45 PM
 */

namespace App\Console\Commands;

use App\Services\CorpSelfService;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use App\Models\WechatDepartment as DepModel;
use Illuminate\Support\Facades\Log;
use App\Models\WechatCorpAccount as CorpAccountModel;


/**
 * 拉取企业微信部门成员
 *
 * Class Push
 * @package App\Console\Commands
 */
class WechatCorpAccount extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wechat:corp_account';


    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '拉取企业微信内部部门成员';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }


    /**
     *
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle()
    {
        $depList = DepModel::query()->select('id', 'corp_id', 'department_id')->get();
        if ($depList->isEmpty()) {

            return false;
        }
        $client  = new Client();
        $service = new CorpSelfService();
        $token   = $service->getAccessToken();
        foreach ($depList as $dep) {
            $response = $client->request('GET', sprintf($service->api['self_user_list'], $token, $dep->department_id));
            if ($response->getStatusCode() != 200) {
                continue;
            }
            $contents = $response->getBody()->getContents();
            $data     = json_decode($contents, true);
            $userlist = $data['userlist'] ?? [];
            Log::info('同步自建应用企业部门成员，共计：' . count($userlist) . '条');
            foreach ($userlist as $item) {
                $account                = CorpAccountModel::query()->firstOrNew([
                    'corp_id' => $dep->corp_id, 'user_id' => $item['userid']
                ]);
                $account->department_id = $dep->department_id ?? '';
                $account->user_name     = $item['name'] ?? '';
                $account->save();
            }
        }
        Log::info('同步自建应用企业部门成员完成');
    }

}
